package cn.kgc.psringboot.controller;

import cn.kgc.psringboot.entity.User;
import cn.kgc.psringboot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

/**
 * @author: mosin
 * @version: v1.0  2022/11/17
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("register")
    public String  register(User user){
        Boolean  b =  userService.saveUser(user);
        if(b){
            return "redirect:/log.jsp";
        }else {
            return "register";
        }
    }


    @PostMapping("login")
    public String login(User user){

        // 登录认证   subject
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        // 判定用户是否勾选记住我
        if(user.getRememberMe()!=null){
            // 开启记住我的功能
            usernamePasswordToken.setRememberMe(true);
        }
        subject.login(usernamePasswordToken);
        return  "redirect:/index.jsp";
    }


    @RequestMapping("logout")
    public String logout(){
        //退出登录  subject
        Subject subject = SecurityUtils.getSubject();
        subject.logout();  // 销毁session
        return "redirect:/log.jsp";
    }


    @RequiresRoles({"admin"})
    @RequiresPermissions({"user:add"})
    @RequestMapping("add")
    @ResponseBody
    public Object add(){

        HashMap<String, Object> map = new HashMap<>();
        map.put("msg", "添加用户信息");
        map.put("code", 200);
        return map;
    }

    @RequiresRoles({"admin"})
    @RequiresPermissions({"user:delete"})
    @RequestMapping("delete")
    @ResponseBody
    public Object delete(Integer id){
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg", "删除用户信息"+id);
        map.put("code", 200);
        return map;
    }

}
